<template>
  <div class="tableRow">
    <el-row class="toolbar">
      <el-button type="primary" icon="el-icon-plus" size="mini" plain @click="handleAdd"
                 v-permission="'system:area:add'">
        新增
      </el-button>
      <el-button type="info" icon="el-icon-edit" :disabled="dialog.isBatchEditDisabled" size="mini" plain
                 @click="handleEdit" v-permission="'system:area:edit'"> 编辑
      </el-button>
      <el-button type="danger" icon="el-icon-delete" :disabled="dialog.isBatchRemoveDisabled" size="mini" plain
                 @click="handleBatchDelete" v-permission="'system:area:remove'"> 删除
      </el-button>
    </el-row>
    <tree-table :columns="columns" :data="data" :operates="operates"
                @handle-selection-change="handleSelectionChange"/>
    <el-dialog :title="dialog.title"
               :visible.sync="dialog.dialogFormVisible"
               :modal-append-to-body="false"
               :destroy-on-close="false"
               @close="closeDialog"
               width="600px">
      <el-form :model="areaModel" ref="areaForm" label-width="100px" :rules="areaFormRules" size="small">
        <el-form-item label="上级区域" prop="parentId">
          <!--el-tree-select  文档地址 https://ayiaq1.github.io/el-tree-select/website/#/components/ElTreeSelect-->
          <el-tree-select v-model="areaModel.parentId" :selectParams="dialog.selectParams"
                          :treeParams="dialog.treeParams"
                          @searchFun="searchFun" ref="treeSelect" @node-click="parentAreaChange"/>
        </el-form-item>

        <el-form-item label="区域名称" prop="name">
          <el-input v-model="areaModel.name" placeholder="区域名称"/>
        </el-form-item>

        <el-form-item label="显示排序" prop="orderNum">
          <el-input-number v-model="areaModel.orderNum" value="1" :min="1" label="显示顺序"/>
        </el-form-item>

        <el-form-item label="区域编码" prop="code">
          <el-input v-model="areaModel.code" placeholder="区域编码"/>
        </el-form-item>
        <el-form-item label="区化经纬度" prop="lonLat">
          <el-input v-model="areaModel.lonLat"  placeholder="区划经纬度"/>
        </el-form-item>
        <el-form-item label="上传区划地图" prop="vectorId">
          <el-input v-model="areaModel.vectorId" hidden/>
          <el-upload
            ref="upload"
            class="upload-demo"
              :action="uploadAction"
              :on-success="handleAvatarSuccess"
              :auto-upload="false"
              >
            <el-button size="small" slot="trigger" type="primary">读取文件</el-button>
            <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
            <el-button v-if="areaModel.vectorId" size="small" @click="downGeoJson">下载</el-button>
            <div slot="tip" class="el-upload__tip">只能上传json/geojson文件</div>
          </el-upload>
         
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-switch v-model="areaModel.status" active-color="#13ce66" inactive-color="#ff4949"
                     active-text="正常"
                     inactive-text="停用"
                     active-value="0"
                     inactive-value="1">
          </el-switch>
        </el-form-item>
        <div id="mapContainer">
            <open-map :mapWidth="'580px'" @currentPosition="getMapPosition" :mapHeight="'200px'" :lonLat="areaModel.lonLat" :vectorId="areaModel.vectorId"></open-map>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.dialogFormVisible=false" size="medium">取 消</el-button>
        <el-button type="primary" @click="submitForm" size="medium">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import {Component, Ref, Vue} from 'vue-property-decorator';
import TreeTable from '@/components/TreeTable/TreeTable.vue';

import {
  addArea,
  checkAreaNameUnique,
  areaTreeSelectData,
  getAreaTreeTableData,
  checkAreaCodeUnique,
  removeArea,
  updateArea
} from '@/api/area';
import {validateForm} from '@/utils';
import OpenMap from '@/components/OpenMap.vue';
@Component({components: {TreeTable,OpenMap}})
export default class Area extends Vue {
  data: Array<any> = [];
  openMap:any;
  uploadAction = process.env.VUE_APP_BASE_API  +'/resources/upload';
  @Ref('areaForm') private areaForm: any;
  @Ref('treeSelect') private treeSelect: any;
  @Ref('upload') upload:any;
  fileList =[];
  columns: any = [
    {
      label: 'ID',
      prop: 'id',
      width: 150
    },
    {
      label: '名称',
      prop: 'name'
    },
    {
      label: '编码',
      prop: 'code'
    },
    {
      label: '经纬度',
      prop: 'lonLat'
    },
    {
      label: '排序',
      prop: 'orderNum'
    },
    {
      label: '状态', prop: 'status', sortable: 'custom', render: function (createElement, row) {
        if (row && row.row && row.row.status === '0') {
          return createElement('el-tag', {
              attrs: {
                type: 'success'
              }
            }, ['正常']
          );
        } else if (row && row.row && row.row.status === '1') {
          return createElement('el-tag', {
              attrs: {
                type: 'warning'
              }
            }, ['停用']
          );
        } else {
          return createElement('el-tag', {
              attrs: {
                type: 'danger'
              }
            }, ['未知']
          );
        }
      }
    },
    {label: '创建时间', prop: 'createTime', sortable: 'custom', width: 160, showOverflowTooltip: true},
    {label: '备注', prop: 'remark', sortable: 'custom', showOverflowTooltip: true},
  ];
  operates: any = {
    width: 200,
    fixed: 'right',
    list: [
      {
        label: '编辑',
        type: 'warning',
        icon: 'el-icon-edit',
        plain: true,
        disabled: () => {
          return false;
        },
        permission: 'system:area:edit',
        method: (index, row) => {
          this.handleEdit(index, row);
        }
      },
      {
        label: '删除',
        type: 'danger',
        icon: 'el-icon-delete',
        plain: true,
        disabled: () => {
          return false;
        },
        permission: 'system:area:remove',
        method: (index, row) => {
          this.handleDelete(index, row);
        }
      }
    ]
  };
  areaModel: any = {
    parentId: 0,
    name: '',
    orderNum: 1,
    code: '',
    status: '0',
    vectorId:'',
    lonLat:'',
  };
  areaFormRules: any = {
    parentId: [
      {validator: this.validateParentNotSelf, trigger: 'change'},
    ],
    name: [
      {required: true, message: '区域名称不能为空', trigger: ['blur', 'change']},
      {validator: this.validateAreaNameUnique, trigger: 'blur'},
    ],
    orderNum: [
      {required: true, message: '显示排序不能为空', trigger: ['blur']}
    ],
    code: [
      {required: true, message: '区域编码不能为空', trigger: ['blur', 'change']},
      {validator: this.validateCodeUnique, trigger: ['blur', 'change']}
    ]
  };
  dialog: any = {
    dialogFormVisible: false,
    title: '对话框',
    isEdit: false,
    isBatchEditDisabled: true,
    isBatchRemoveDisabled: true,
    formData: [],
    selectParams: {
      clearable: true,
      placeholder: '请选择上级区域'
    },
    treeParams: {
      clickParent: true,
      filterable: true,
      accordion: true,
      data: [],
      props: {
        children: 'children',
        label: 'label',
        disabled: 'disabled',
        value: 'id'
      }
    }
  };

  /*验证区域名称是否唯一*/
  validateAreaNameUnique(rule: any, value: any, callback: any) {
    checkAreaNameUnique({
      name: value,
      id: this.areaModel.id,
      parentId: this.areaModel.parentId
    }).then((res: any) => {
      if (res.data && res.data === '0') {
        callback();
      } else {
        callback(new Error('区域已经存在'));
      }
    }).catch((err: any) => {
      console.error(err);
      callback(new Error('区域已经存在'));
    })
  }

  submitUpload() {
      this.upload.submit();
  }

  getMapPosition(val:string){
   
    this.areaModel.lonLat = val +'';
  }

  downGeoJson(){
    const link = document.createElement('a');
    link.href = process.env.VUE_APP_BASE_API +'resources/file/' + this.areaModel.vectorId;
    link.setAttribute('download',this.areaModel.name + ".json");
    link.click();
  }
  validateCodeUnique(rule: any, value: any, callback: any) {
    checkAreaCodeUnique({
      code: value,
      id: this.areaModel.id
    }).then((res: any) => {
      if (res.data && res.data === '0') {
        callback();
      } else {
        callback(new Error('区域编码已经存在'));
      }
    }).catch((err: any) => {
      console.error(err);
      callback(new Error('区域编码已经存在'));
    })
  }

  /*上级区域不能是自己本身*/
  validateParentNotSelf(rule: any, value: any, callback: any) {
    if (value === this.areaModel.id) {
      callback(new Error('上级区域不能是自己本身'));
    } else {
      callback();
    }
  }

  /*新增*/
  handleAdd() {
    this.dialog.title = '新增区域';
    this.dialog.isEdit = false;
    areaTreeSelectData().then((response: any) => {
      if (response.data) {
        this.dialog.treeParams.data = response.data;
        this.dialog.dialogFormVisible = true;
      }
    }).catch((e) => {
      console.error(e);
    });
  }

  /*编辑*/
  handleEdit(index: number, row: any) {
    this.dialog.title = '编辑区域';
    this.dialog.isEdit = true;
    areaTreeSelectData().then((response: any) => {
      this.areaModel = Object.assign({}, row || this.dialog.formData[0]);
      if (response.data) {
        this.dialog.treeParams.data = response.data;
        this.dialog.dialogFormVisible = true;
      }
    }).catch((e) => {
      console.error(e);
    });
  }

  parentAreaChange(data:any,node:any,mv:any){
    if(this.areaModel.code){
      if(this.areaModel.code.length > data.code.length){
        this.areaModel.code = data.code + this.areaModel.code.substring(data.code.length);
      }else{
        this.areaModel.code = data.code;
      }
    }else{
      this.areaModel.code = data.code;
    }
   
  }

  handleAvatarSuccess(res, file) {
    this.areaModel.vectorId = res.data.id;
  }

  /*批量删除*/
  handleBatchDelete() {
    //删除
    this.$confirm('确定要删除选定区域吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const ids: Array<any> = [];
      this.dialog.formData.forEach((item, index) => {
        ids[index] = item.id;
      });
      return removeArea({'ids': ids});
    }).then((response: any) => {
      this.getData();
      this.$message.success(response.msg);
    }).catch((e) => {
      console.error(e);
    });
  }

  /*删除*/
  handleDelete(index: number, row: any) {
    this.$confirm('确定要删除该区域吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      return removeArea({'ids': [row.id]});
    }).then((response: any) => {
      this.getData();
      this.$message.success(response.msg);
    }).catch((e) => {
      console.error(e);
    });
  }

  submitForm(): void {
    this.areaForm.validate((valid: boolean) => {
      if (valid) {
        delete this.areaModel.children;
        if (this.dialog.isEdit) {
          //编辑
          updateArea(this.areaModel).then((response: any) => {
            this.getData();
            this.reset();
            this.dialog.dialogFormVisible = false;
            this.$message.success(response.msg);
          }).catch((e) => {
            console.error(e);
            validateForm(e.data, this.areaForm, this.areaFormRules);
          });
        } else {
          //新增
          addArea(this.areaModel).then((response: any) => {
            this.getData();
            this.reset();
            this.dialog.dialogFormVisible = false;
            this.$message.success(response.msg);
          }).catch((e) => {
            console.error(e);
            validateForm(e.data, this.areaForm, this.areaFormRules);
          });
        }
      }
    });
  }

  handleVectorSuccess(res, file) {
    this.areaModel.vectorId = res.data.id;
    this.dialog.imageUrl = process.env.VUE_APP_BASE_API +res.data.resource;
  }

  /*选中事件*/
  handleSelectionChange(val): void {
    if (val) {
      this.dialog.isBatchRemoveDisabled = val.length <= 0;
      this.dialog.isBatchEditDisabled = val.length !== 1;
    }
    this.dialog.formData = val;
  }

  /*重置表单*/
  reset(): void {
    this.areaModel = {
      parentId: 0,
      name: '',
      orderNum: 1,
      code: '',
      status: '0',
      lanLot:'',
      vectorId:''
    };
    (this as any).resetForm('areaForm');
  }

  /*关闭对话框*/
  closeDialog() {
    this.$nextTick(() => {
      this.reset();
    });
  }

  /*获取数据*/
  getData() {
    getAreaTreeTableData().then(response => {
      this.data = response.data;
    }).catch((e) => {
      console.error(e);
    });
  }

  searchFun(value: any): void {
    this.treeSelect.filterFun(value);
  }


  mounted() {
    this.getData();
  }
}
</script>

<style scoped lang="scss">

</style>

